/*
 *  Copyright 2011 Alexey Andreev.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.xthl.core;

import java.util.HashSet;
import java.util.Set;
import org.nop.core.Application;
import org.nop.core.ApplicationHandler;
import org.nop.sql.CloseableDataManager;
import org.nop.sql.DataManagerFactory;
import org.nop.sql.DataResult;
import org.nop.sql.QueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xthl.core.data.BlockSource;

/**
 *
 * @author Alexey Andreev
 */
public class BlocksFeatureImpl implements BlocksFeature {
    private static final Logger logger = LoggerFactory.getLogger(BlocksFeatureImpl.class);
    private Application app;
    private Set<String> blocks = new HashSet<String>();

    public BlocksFeatureImpl(Application app) {
        this.app = app;
        blocks.add(MenuBlock.class.getName());
        blocks.add(LoginBlock.class.getName());
        app.addApplicationHandler(new ApplicationHandler() {
            @Override
            public void started() {
                start();
            }
        });
    }

    @Override
    public void registerBlock(Class<? extends BlockRenderer> rendererType) {
        if (blocks.add(rendererType.getName())) {
            logger.info("Block registered: " + rendererType.getName());
        }
    }
    
    private void start() {
        CloseableDataManager dataManager = app.get(DataManagerFactory.class).createDataManager();
        try {
            logger.info("Trying to create special blocks");
            QueryBuilder qb = dataManager.getQueryBuilder();
            BlockSource block = qb.get(BlockSource.class);
            DataResult result = dataManager.exec(qb.with(block)
                    .filter(block.type().eq(BlockSource.SPECIAL_TYPE))
                    .fetch(block.title()));
            while (result.next()) {
                blocks.remove(result.getString(1));
            }
            result = dataManager.exec(qb.with(block).fetch(qb.max(block.position())));
            result.next();
            int pos = result.getInt(1);
            for (String blockName : blocks) {
                int id = dataManager.nextInt(BlockSource.ID_SEQUENCE);
                dataManager.exec(qb.insertInto(block)
                        .field(block.id(), id)
                        .field(block.type(), BlockSource.SPECIAL_TYPE)
                        .field(block.position(), pos++)
                        .field(block.enabled(), false)
                        .field(block.title(), blockName)
                        .field(block.content(), qb.getNull())
                        .field(block.version(), 0));
            }
            dataManager.commit();
        } finally {
            dataManager.close();
        }
    }
}
